package com.crane.framework.response;

import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 使用 @ControllerAdvice & ResponseBodyAdvice 拦截Controller方法默认返回参数，统一处理返回值/响应体
 *
 * @author : ten.x
 * @date : 2022-03-16
 */
@ControllerAdvice(basePackages = "com.crane")
@ResponseBody
@Slf4j
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {

  /** 标记名称 */
  public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

  @Override
  public boolean supports(
      MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
    return MappingJackson2HttpMessageConverter.class.isAssignableFrom(aClass);
  }

  @Override
  public Object beforeBodyWrite(
      Object body,
      @NotNull MethodParameter methodParameter,
      @NotNull MediaType mediaType,
      @NotNull Class<? extends HttpMessageConverter<?>> aClass,
      @NotNull ServerHttpRequest serverHttpRequest,
      @NotNull ServerHttpResponse serverHttpResponse) {
    if (body instanceof CommonResult) {
      return body;
    } else if (body == null) {
      return CommonResult.success();
    } else if (body instanceof String) {
      return CommonResult.success(body);
    }
    return CommonResult.success(body);
  }
}
